<?php
class IndexController extends Apps_Controller_Action_Default {
    const PRIVATE_CAPTCHA_KEY = '760211';

	public function indexAction() {
        // XmlHttpRequest resolve
        $rq = $this->_request;
        if($rq->isXmlHttpRequest() && $ajax = $rq->getParam('ajax')) {
            return $this->_forward('ajax-' . $ajax);
        }

		$this->_forward('index', 'home', 'default');
	}

	//translate
	public function translateAction() {
	    $rq   = $this->_request;
	    $lang = $rq->getParam('lang');

	    if($lang !== 'en' && $lang !== 'vi') {
	        $lang = 'en';
	    }

	    $session = new Zend_Session_Namespace('sessionLanguage');
	    $session->lang = $lang;

	    $backtrackUrl = $this->getBacktrackUrl();

	    //echo $backtrackUrl;die;

	    if(!$backtrackUrl) {
	        $this->_redirect('/');
	    }

        $backtrackUrlArray = explode('/', $backtrackUrl);
        if(isset($backtrackUrlArray[2]) && $backtrackUrlArray[2] == 'translate') {
            $this->_redirect('/index/index/lang/'.$lang);
        }

	    $backtrackUrl = str_replace('/lang/'.$lang, '/', $backtrackUrl);

        $this->_redirect($backtrackUrl);
	}

    // Ajax/ Order
    public function ajaxListReferenceOrderAction() {
        $this->ajaxOnly();

        $r = array();

        $p = $this->_getParam('p');

        $tb = new M_DbTable_Order();
        $d  = $tb->listReferenceByOrderType($p);

        if($d) {
            $dMapper = new M_Tool_DataMapper();
            $r       = $dMapper->mapKeyValue($d, 'id', 'name', array('' => ''));
        }
        echo Zend_Json::encode($r);
    }

    /* CAPTCHA
     * captchaCode = md5(subtr(md5($captcha), 0, $length) . self::PRIVATE_CAPTCHA_KEY);
     * */
    public function captchaAction() {
        $captchaSession = new Zend_Session_Namespace('captchaSession');

        $length = $this->_request->getParam('len') ? $this->_request->getParam('len') : 6;

        $md5     = md5(rand());
        $text    = substr($md5, 0, $length);

        $captcha = imagecreatefrompng("../public/static/default/images/captcha.png");

        $font = 6;
        for($i = 0; $i < 10; $i++) {
            imageline($captcha, rand(0,50), rand(0,200), rand(0,400), rand(0,10), rand(0,100));
        }

        $imageWidth  = imagesx($captcha);
        $imageHeight = imagesy($captcha);

        $textWidth  = imagefontwidth($font) * $length;
        $textHeight = imagefontheight($font);
        $textColor  = imagecolorallocate($captcha, 1, 1, 1);

        imagestring($captcha, $font, ($imageWidth - $textWidth)/2 , ($imageHeight - $textHeight)/2, $text, $textColor);

        $captchaSession->captcha_code = md5($text . self::PRIVATE_CAPTCHA_KEY);

        header("Content-type: image/png");
        imagepng($captcha);
        imagedestroy($captcha);
        exit();
    }

}